//
//  DMTabBarController.swift
//  DMTabBar
//
//  Created by Apple on 2017/2/13.
//  Copyright © 2017年 AF. All rights reserved.
//

import UIKit

class DMTabBarController: UITabBarController
{
    var tabBarBgImg : UIImageView?
    var tabBarBgImgSelected : UIImageView?
    var selectedButton : UIButton? // 标记选中的按钮
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.lightGray
        
        
        return;
        // 移除系统tabBar，添加自定义tabBar
        self.tabBar.removeFromSuperview()
        let customTabBar = UIView(frame: self.tabBar.frame)
        customTabBar.backgroundColor = .white
        self.view.addSubview(customTabBar)
        
        
        // 添加两个控制器到tabBar
        self.viewControllers = [UINavigationController(rootViewController: HomeViewController()), UINavigationController(rootViewController: GameViewController())]
        
        
        // 添加按钮到自定义的tabBar
        let btnsCount : Int = self.viewControllers!.count
        for temp in 0..<btnsCount
        {
            let btnH : CGFloat = 60
            let btnW : CGFloat = UIScreen.main.bounds.size.width / CGFloat(btnsCount)
            let btnX : CGFloat = CGFloat(temp) * btnW
            let btnY : CGFloat = 0
            let btn = UIButton(frame: CGRect(x: btnX, y: btnY, width: btnW, height: btnH))
            customTabBar.addSubview(btn)
            btn.tag = temp
//            btn.addTarget(self, action: "didClickButton:", forControlEvents: UIControlEvents.TouchUpInside)
//            btn.setBackgroundImage(UIImage(named: "frame-new&hot-top-normal"), forState: UIControlState.Normal)
//            btn.setBackgroundImage(UIImage(named: "frame-new&hot-top-pressed"), forState: UIControlState.Selected)
            
            if temp == 0
            {
                btn.isSelected = true
                self.selectedButton = btn
            }
            
            // 设置按钮背景图片
            if temp == 0
            {
                btn.setImage(UIImage(named: "tab-video-line"), for: .normal)
                btn.setImage(UIImage(named: "tab-video-solid"), for: .selected)
            }
            else if temp == 1
            {
                btn.setImage(UIImage(named: "tab-game-line"), for: .normal)
                btn.setImage(UIImage(named: "tab-game-solid"), for: .selected)
            }
        }
    }
    
    func didClickButton (button : UIButton) -> Void
    {
        self.selectedButton?.isSelected = false
        button.isSelected = true
        self.selectedButton = button
        self.selectedIndex = button.tag
    }
    
    
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        print("UITabBarItem: \(item)")
    }
}
